package com.my.demo.auth.service;

import com.my.demo.auth.entity.Account;
import com.my.demo.auth.repository.AccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * Created by LeiXuMeng on 2017/7/14.
 */
@Service
public class MongoUserDetailService implements UserDetailsService {

    @Autowired
    private AccountRepository accountRepository;

    @Override
    public UserDetails loadUserByUsername(String name) throws UsernameNotFoundException {
        // 通过用户名获取用户信息
        Account account = accountRepository.findByName(name);
        if (account != null) {
            // 创建spring security安全用户
            User user = new User(account.getName(), account.getPassword(),
                    AuthorityUtils.createAuthorityList(account.getRoles()));
            return user;
        } else {
            throw new UsernameNotFoundException("用户[" + name + "]不存在");
        }

    }
}
